package com.example.sunmiv1.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.activity.member.EditLabelActivity;
import com.example.sunmiv1.entity.GetUserLabelInfo;
import com.example.sunmiv1.entity.LoginEntity;
import com.example.sunmiv1.entity.MemberInfoBean;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.vm.UpdateInfoViewModel;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UpdateInfoActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.updateInfo_name)
    EditText updateInfoName;
    @BindView(R.id.updateInfo_phone)
    EditText updateInfoPhone;
    @BindView(R.id.updateInfo_vipType)
    Spinner updateInfoVipType;
    @BindView(R.id.updateInfo_grade)
    Spinner updateInfoGrade;
    @BindView(R.id.updateInfo_balance)
    EditText updateInfoBalance;
    @BindView(R.id.updateInfo_birthday)
    TextView updateInfoBirthday;
    @BindView(R.id.updateInfo_save)
    TextView updateInfoSave;
    @BindView(R.id.updateInfoPass_off)
    ImageView updateInfoPassOff;
    @BindView(R.id.updateInfoPass_pass)
    EditText updateInfoPassPass;
    @BindView(R.id.updateInfoPass_login)
    TextView updateInfoPassLogin;
    @BindView(R.id.updateInfoPass_confirm)
    TextView updateInfoPassConfirm;
    @BindView(R.id.updateInfoPass_linear)
    LinearLayout updateInfoPassLinear;
    @BindView(R.id.updateInfo_gradeLin)
    LinearLayout updateInfoGradeLin;
    @BindView(R.id.updateInfo_vipTypeLin)
    LinearLayout updateInfoVipTypeLin;
    @BindView(R.id.updateInfo_label)
    TextView updateInfoLabel;
    @BindView(R.id.updateInfo_gradeLinView)
    View updateInfoGradeLinView;
    @BindView(R.id.updateInfo_vipTypeLinView)
    View updateInfoVipTypeLinView;
    private Context context;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private MemberInfoBean memberinfoBean;
    private int gradeIndex = 0;
    private int vipType = 3;//3常規會員   2plus會員
    private List<String> vipTypeList = new ArrayList<>();
    private List<String> gradeNameList = new ArrayList<>();
    private List<MemberInfoBean.GradeDataBean> gradeList = new ArrayList<>();
    private static final String TAG = "UpdateInfoActivity";

    //nfc
    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;
    private boolean isSupportNfc, isOpenNfc;

    private Intent intent;
    private LoginEntity loginEntity;

    private UpdateInfoViewModel mViewModel;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    updateInfoName.setText(memberinfoBean.getVip().getZname());
                    updateInfoPhone.setText(memberinfoBean.getVip().getMobile_phone());
//                    updateInfoCardNum.setText(memberinfoBean.getVip().getCard_key());
                    updateInfoBalance.setText(memberinfoBean.getVip().getBalance());
                    //updateInfoBirthday.setText(memberinfoBean.getVip().getAddtime());
                    if ("3".equals(memberinfoBean.getVip().getPlus_type())) {
                        vipType = 3;
                    } else {
                        updateInfoVipTypeLin.setVisibility(View.GONE);
                        updateInfoVipTypeLinView.setVisibility(View.GONE);
                        updateInfoGradeLin.setVisibility(View.GONE);
                        updateInfoGradeLinView.setVisibility(View.GONE);
                        vipType = 2;
                    }
                    for (MemberInfoBean.GradeDataBean gradeDataBean : memberinfoBean.getGradeData()) {
                        gradeList.add(gradeDataBean);
                        gradeNameList.add(gradeDataBean.getCardname());
                    }
                    setGradeAdapter();
                    vipTypeList.add("普通會員");
                    vipTypeList.add("PLUS會員");
                    setVipTypeAdapter();
                    break;
                case 2:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_update_info);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.updateInfoTitle);
        context = this;
        aCache = ACache.get(context);
        Gson gson = new Gson();
        loginEntity = gson.fromJson(aCache.getAsString("loginInfo"), LoginEntity.class);
        loadingDialog = new LoadingDialog(context);
        mViewModel=new UpdateInfoViewModel(this,loginEntity);
        initListener();
        getInfo();
        //nfc
        /*PackageManager packageManager = this.getPackageManager();
        isSupportNfc = packageManager.hasSystemFeature(PackageManager.FEATURE_NFC);
        Log.e(TAG, "onCreate: isSupportNfc=" + isSupportNfc);
        if (isSupportNfc) {
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
            pi = PendingIntent.getActivity(this, 0, new Intent(this, getClass())
                    .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
            if (mNfcAdapter != null && !mNfcAdapter.isEnabled()) {
                isOpenNfc = false;
            } else {
                isOpenNfc = true;
            }
        }
        if (mNfcAdapter != null && !isOpenNfc) {
            Toast.makeText(context, "如需使用nfc功能，請到設置中開啓！", Toast.LENGTH_SHORT).show();
        }*/
    }

    private void setGradeAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select_right, gradeNameList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drop_right);
        updateInfoGrade.setAdapter(arrayAdapter);
        for (int i = 0; i < gradeList.size(); i++) {
            if (memberinfoBean.getVip().getGrade_id().equals(gradeList.get(i).getId())) {
                updateInfoGrade.setSelection(i);
                break;
            }
        }
    }

    private void setVipTypeAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select_right, vipTypeList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drop_right);
        updateInfoVipType.setAdapter(arrayAdapter);
        if (vipType == 3) {
            updateInfoVipType.setSelection(0);
        } else {
            updateInfoVipType.setSelection(1);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        /*if (mNfcAdapter != null && isSupportNfc && isOpenNfc) {
            mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
        }*/
        getUserLabel();
    }

    /*@Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // Toast.makeText(context, "onNewIntent", Toast.LENGTH_SHORT).show();

        String ex_id;
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String num1 = ByteArrayToHexString(tagFromIntent.getId());
        String num2 = flipHexStr(num1);
        Log.e(TAG, "onNewIntent: 1=" + num2);
        String num = "";
        if (num2.length() > 10) {
            try {
                num = ByteArrayTohexHepler.hex2String(num2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Long cardNo = Long.parseLong(num2, 16);
            Log.e(TAG, "onNewIntent: 2=" + cardNo);
            num = cardNo.toString();
        }
        if (num.length() != 10) {
            while (num.length() < 10) {
                num = "0" + num;
            }
        }
        ex_id = num;
        Log.e("==================", ex_id);
        //Toast.makeText(getApplicationContext(), num, Toast.LENGTH_SHORT).show();
//        updateInfoCardNum.setText(ex_id);
//        updateInfoCardNum.setSelection(ex_id.length());
    }*/

    private void initListener() {
        updateInfoGrade.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                gradeIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        updateInfoVipType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    vipType = 3;
                } else {
                    vipType = position + 1;
                }
                if (position == 0) {
                    for (int i = 0; i < gradeList.size(); i++) {
                        if (memberinfoBean.getVip().getGrade_id().equals(gradeList.get(i).getId())) {
                            updateInfoGrade.setSelection(i);
                            break;
                        }
                    }
                    updateInfoGradeLin.setVisibility(View.VISIBLE);
                    updateInfoGradeLinView.setVisibility(View.VISIBLE);
                } else {
                    updateInfoGradeLin.setVisibility(View.GONE);
                    updateInfoGradeLinView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        updateInfoBalance.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().contains(".")) {
                    if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > 2) {
                        charSequence = charSequence.toString().subSequence(0, charSequence.toString().indexOf(".") + 3);
                        updateInfoBalance.setText(charSequence);
                        updateInfoBalance.setSelection(charSequence.length());
                    }
                }
                if (charSequence.toString().trim().substring(0).equals(".")) {
                    charSequence = "0" + charSequence;
                    updateInfoBalance.setText(charSequence);
                    updateInfoBalance.setSelection(2);
                }

                if (charSequence.toString().startsWith("0") && charSequence.toString().trim().length() > 1) {
                    if (!charSequence.toString().substring(1, 2).equals(".")) {
                        updateInfoBalance.setText(charSequence.subSequence(1, 2));
                        updateInfoBalance.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }

    private void getInfo() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("vid", getIntent().getStringExtra("vid"));
            jsonObject.put("storeTag", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            HttpUtils.post(context, Common.GET_MEMBER_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    memberinfoBean = GsonUtils.JsonToBean(text, MemberInfoBean.class);
                    Message msg = new Message();
                    mViewModel.init(memberinfoBean);
                    if (memberinfoBean.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.title_back, R.id.updateInfo_birthday, R.id.updateInfo_save,
            R.id.updateInfoPass_off, R.id.updateInfoPass_login, R.id.updateInfoPass_confirm, R.id.updateInfoPass_linear,
            R.id.updateInfo_label})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.updateInfo_label:
                intent = new Intent(context, EditLabelActivity.class);
                intent.putExtra("vid",getIntent().getStringExtra("vid"));
                intent.putExtra("list", (Serializable) labelList);
                startActivity(intent);
                break;
            case R.id.title_back:
                finish();
                break;
            case R.id.updateInfo_save:
                saveBt();
                break;

            case R.id.updateInfoPass_off:
                updateInfoPassPass.setText("");
                updateInfoPassLinear.setVisibility(View.GONE);
                break;
            case R.id.updateInfoPass_login:
                updateInfoPassPass.setText("");
                updateInfoPassLinear.setVisibility(View.GONE);
                break;
            case R.id.updateInfoPass_confirm:
                saveUpdate();
                break;
            case R.id.updateInfoPass_linear:
                break;
        }
    }

    private void saveUpdate() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("platform_type", aCache.getAsString("platform_type"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("operator_identity_id", aCache.getAsString("uid"));
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            }
            jsonObject.put("modify_vip_code", updateInfoPassPass.getText().toString().trim());
            JSONObject vip_edit_info = new JSONObject();
//            vip_edit_info.put("vip_type", vipType);//3常規會員   2plus會員
            vip_edit_info.put("vip_id", getIntent().getStringExtra("vid"));
            vip_edit_info.put("grade_id", gradeList.size() == 0 ? 0 : gradeList.get(gradeIndex).getId());
            vip_edit_info.put("mobile_phone", updateInfoPhone.getText().toString().trim());
            vip_edit_info.put("balance", TextUtils.isEmpty(updateInfoBalance.getText().toString().trim()) ?
                    0 : updateInfoBalance.getText().toString().trim());
            vip_edit_info.put("vip_name", updateInfoName.getText().toString().trim());
//            if (vipType==2){
                vip_edit_info.put("operate_days_type", "0");
//            }
            jsonObject.put("vip_edit_info",vip_edit_info);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.VIP_EDIT, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("message"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            mViewModel.saveEntity();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取當前會員標籤
     */
    private GetUserLabelInfo getUserLabelInfo;
    private List<GetUserLabelInfo.DataBean.ListBean> labelList = new ArrayList<>();

    private void getUserLabel() {
        labelList.clear();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("vid", getIntent().getStringExtra("vid"));
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.GET_USER_LABEL, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    getUserLabelInfo = GsonUtils.JsonToBean(text, GetUserLabelInfo.class);
                    if (getUserLabelInfo.getStatus() == 1) {
                        labelList.addAll(getUserLabelInfo.getData().getList());
                        String labels = "";
                        for (int i = 0; i < getUserLabelInfo.getData().getList().size(); i++) {
                            labels = labels + getUserLabelInfo.getData().getList().get(i).getName() + ",";
                        }
                        if (!TextUtils.isEmpty(labels)) {
                            updateInfoLabel.setText(labels.substring(0, labels.length() - 1));
                        }
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void saveBt(){
        if ("3".equals(aCache.getAsString("userType"))) {
            updateInfoPassLinear.setVisibility(View.VISIBLE);
        } else {
            saveUpdate();
        }
    }
}
